package com.zyjc.city.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zyjc.city.constant.TimeFormat;
import com.zyjc.city.entity.AreaPerson;
import com.zyjc.city.mapper.AreaPersonMapper;
import com.zyjc.city.model.ApiResult;
import com.zyjc.city.model.dto.AreaPersonDto;
import com.zyjc.city.model.dto.TransportDto;
import com.zyjc.city.model.params.AreaPersonIn;
import com.zyjc.city.model.params.TransportIn;
import com.zyjc.city.service.AreaPersonService;
import com.zyjc.city.util.BeanTransUtil;
import com.zyjc.city.util.CaffeineUtil;
import com.zyjc.city.util.SnowflakeId;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 区域游客人数表 服务实现类
 * </p>
 *
 * @author ckj
 * @since 2024-04-01
 */
@Service
@Slf4j
public class AreaPersonServiceImpl extends ServiceImpl<AreaPersonMapper, AreaPerson> implements AreaPersonService {

    @Override
    public TransportDto getData(TransportIn transportIn) {
        LambdaQueryWrapper<AreaPerson> query = new LambdaQueryWrapper<>();
        query.eq(AreaPerson::getAreaId, transportIn.getAreaId());
        query.between(AreaPerson::getDateTime, transportIn.getStartTime(), transportIn.getEndTime());
        List<AreaPerson> areaData = this.list(query);
        if (CollectionUtil.isEmpty(areaData)) {
            return TransportDto.builder().areaId(transportIn.getAreaId()).timeData(Collections.emptyList()).personData(Collections.emptyList()).totalCount(0).build();
        }
        List<Integer> personData = areaData.stream().map(AreaPerson::getCnt).collect(Collectors.toList());
        List<String> timeData = areaData.stream().map(x -> DateUtil.format(x.getDateTime(), TimeFormat.PATTERN_TIME)).collect(Collectors.toList());
        Integer totalNum = areaData.stream().filter(x -> Objects.nonNull(x.getCntResi())).map(AreaPerson::getCntResi).max((e1, e2) -> e1.compareTo(e2)).get();
        return TransportDto.builder().personData(personData)
                .timeData(timeData)
                .totalCount(totalNum)
                .areaId(transportIn.getAreaId()).build();

    }

    @SneakyThrows
    @Override
    public void getAreaPerson(AreaPersonIn areaPersonIn) {
        log.info("{}同步{}的区域游客数据", LocalDateTime.now(),areaPersonIn.getAreaId());
        String token = (String) CaffeineUtil.get("token");
        areaPersonIn.setTokenCode(token);
        String param = JSON.toJSONStringWithDateFormat(areaPersonIn, TimeFormat.PATTERN_DATETIME_V);
//        String result = CqcHttpUtil.callInterface(HttpUrlEnum.AREA_PERSON.url, param);
        String result = "{\"code\":\"0\",\"data\":[{\"date_time\":\"2024-04-03 11:20:10\",\"cnt_resi\":12450,\"cnt\":89875}],\"description\":\"\",\"success\":true}";
        ApiResult<List<AreaPersonDto>> apiResult = JSON.parseObject(result, new TypeReference<ApiResult<List<AreaPersonDto>>>() {});
        List<AreaPersonDto> data = apiResult.getData();
        //未查询到数据
        if(!Objects.equals(0,apiResult.getCode())||CollectionUtil.isEmpty(data)){
            log.info("未查询到数据入参{}",param);
            return;
        }
        //已同步数据进行去重
        LambdaQueryWrapper<AreaPerson> query = new LambdaQueryWrapper<>();
        query.eq(AreaPerson::getAreaId, areaPersonIn.getAreaId());
        String startTime = DateUtil.format(areaPersonIn.getSTime(), TimeFormat.PATTERN_DATETIME);
        String endTime = DateUtil.format(areaPersonIn.getETime(), TimeFormat.PATTERN_DATETIME);
        query.between(AreaPerson::getDateTime, startTime, endTime);
        List<AreaPerson> areaData = this.list(query);
        //去重规则 区域id和数据采集时间
        Map<String, AreaPerson> syncDataMap = areaData.stream().collect(Collectors.toMap(x -> x.getAreaId() + "-" + DateUtil.format(x.getDateTime(), TimeFormat.PATTERN_DATETIME_V), Function.identity(), (v1, v2) -> v1));
        List<AreaPerson> areaPeople = new ArrayList<>();
        for (AreaPersonDto item : data) {
            Date date = new Date();
            //比对数据
            String key = areaPersonIn.getAreaId() + "-" + DateUtil.format(item.getDateTime(), TimeFormat.PATTERN_DATETIME_V);
            AreaPerson areaPerson = syncDataMap.get(key);
            if (Objects.isNull(areaPerson)) {
                AreaPerson temp = BeanTransUtil.convert(item, AreaPerson.class);
                temp.setAreaId(areaPersonIn.getAreaId());
                temp.setCreateTime(date);
                temp.setId(SnowflakeId.getId());
                areaPeople.add(temp);
            }
        }
        if (CollectionUtil.isNotEmpty(areaPeople)) {
            this.saveOrUpdateBatch(areaPeople);
            log.info("同步数据成功入参:{}，数据共{}条",param,areaPeople.size());
        }
    }
}
